﻿using System.Linq;
using Coder.Workflow.Searcher;
using Coder.Workflow.Stores;
using Fee.Orders;
using Fee.Orders.DesignWorkflow;
using Fee.Orders.PreWorkflow;
using Fee.Stores;
using JwtWebApi.Data;
using JwtWebApi.Filters;
using JwtWebApi.Models.ViewModel;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;

namespace JwtWebApi.Controllers
{
    [Authorize]
    [Route("[controller]")]
    [ApiController]
    [EnableCors]
    public class WorkActivityController : Controller
    {
        private readonly ApplicationDbContext _context;
        private readonly IWorkActivityStore<ApplicationDbContext> _workActivityStore;

        private readonly BudgetOrderManager<ApplicationDbContext> _workflowManager;


        public WorkActivityController(
            ApplicationDbContext context,
            BudgetOrderManager<ApplicationDbContext> workflowManager,
             IWorkActivityStore<ApplicationDbContext> workActivityStore
        )
        {

            _context = context;
            _workActivityStore = workActivityStore;
            _workflowManager = workflowManager;
        }


        [HttpGet("list-flow/{id:int}")]
        public IActionResult List([FromRoute] int id)
        {
            return Json(_workActivityStore.GetByInstance(id));
        }



        [HttpGet("info/{id:int}")]
        public IActionResult GetTask(int id)
        {
            var workflowInstanceItem = _workflowManager.GetWorkActivity(id, true);

            var result = workflowInstanceItem;

            return Json(result);
        }

        [HttpPut("accept/{id:int}")]
        public IActionResult Accept([FromRoute] int id)
        {
            var item = _workflowManager.Assign(id, User.Identity.Name);

            return Json(new
            {
                successed = true,
                acceptInfo = new
                {
                    item.DepositUser,
                    item.AssignTime,
                    item.Status
                }
            });
        }


        [HttpPut("giveup/{id:int}")]
        public IActionResult Giveup([FromRoute] int id)
        {
            var item = _workflowManager.GiveUp(id, User.Identity.Name);

            return Json(new
            {
                successed = true,
                GiveupInfo = new
                {
                    item.DepositUser,
                    item.AssignTime,
                    item.Status
                }
            });
        }




        [HttpGet("get-by-station/{id:int}")]
        public IActionResult GetByStation([FromRoute] int id)
        {
            var delegateOrder = _context.Set<DelegateOrderBase>().Include(f => f.User).Include(f => f.WorkProcess)
                .Where(f => f.ConstructionTask.Station.Id == id).Select(f => f);


            return Ok(delegateOrder);
        }
    }
}